package com.junchenrobot.mes.schedule;

import com.junchenrobot.mes.client.KCClient;
import com.junchenrobot.mes.dao.DeviceDao;
import com.junchenrobot.mes.domain.Device;
import com.junchenrobot.mes.dto.response.VehicleStatusDto;
import com.junchenrobot.mes.dto.response.VehicleStatusListDto;
import com.junchenrobot.mes.enums.DeviceStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 车辆状态定时任务
 *
 * @author SeaWave
 * @date 2023/02/01
 */
@Slf4j
@Component
public class VehicleStatusSchedule {
    
    private final KCClient kcClient;
    
    private final DeviceDao deviceDao;
    
    @Autowired
    public VehicleStatusSchedule(KCClient kcClient, DeviceDao deviceDao) {
        this.kcClient = kcClient;
        this.deviceDao = deviceDao;
    }
    
   // @Scheduled(cron = "0 0/1 * * * ?")
    public void updateDevice() {
        // 车辆状态
        VehicleStatusListDto vehicleStatusListDto = kcClient.vehicleStatus();
        List<VehicleStatusDto> vehicleStatus = vehicleStatusListDto.getVehicleStatus();
        // 同步到数据库
        List<Device> collect = vehicleStatus.stream().filter(Objects::nonNull).map(v -> {
            Device device = new Device();
            device.setDeviceName(v.getVehicleNo());
            device.setDeviceCode(v.getVehicleNo());
            device.setDeviceBattery(String.valueOf(v.getBattery()));
            device.setDeviceStatus(DeviceStatusEnum.isException(v.getStatus()) ? 1 : 0);
            return device;
        }).collect(Collectors.toList());
        deviceDao.updateBatch(collect);
    }




    
}
